<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="关键字">
              <a-input v-model="queryParam.keyWord" placeholder="请输入关键字" @pressEnter="$refs.table.refresh(true)" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div v-if="!$store.getters.isMzRole" class="table-operator">
      <span style="margin-right: 16px;">已选中{{ selectedRowKeys.length }}行</span>
      <a-button type="primary" icon="plus" @click="handleAdd">新增</a-button>
      <a-button icon="delete" @click="handleDeleteBatch">删除</a-button>
    </div>

    <s-table
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      :rowSelection="rowSelection"
      showPagination="auto"
    >
      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>

      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleCheck(record)">查看</a>
          <!-- <a-divider type="vertical" />
          <a @click="handleEdit(record)">编辑</a> -->
          <a-divider type="vertical" />
          <a @click="handleDelete(record)">删除</a>
        </template>
      </span>
    </s-table>

    <create-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOk"
    />
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { getCaseList, deleteCase, addCase } from '@/api/case'
import CreateForm from './CreateForm'

let columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '社会组织名称',
    dataIndex: 'userName'
  },
  {
    title: '社会组织类型',
    dataIndex: 'type'
  },
  {
    title: '业务主管单位',
    dataIndex: 'unitName'
  },
  {
    title: '申报级别',
    dataIndex: 'level'
    // sorter: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    sorter: true
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'Case',
  components: {
    STable,
    Ellipsis,
    CreateForm
  },
  data () {
    // 民政角色不展示操作项
    if (this.$store.getters.isMzRole) {
      columns = columns.filter(v => v.dataIndex != 'action')
    }
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return getCaseList(requestParameters)
          .then(res => {
            console.log(res)
            return res
          })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  filters: {
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    handleDeleteBatch () {
      if (this.selectedRowKeys.length === 0) {
        this.$warning({
          title: '提示',
          content: '请选择需要删除的数据'
        })
      } else {
        console.log(this.selectedRowKeys)
        const arr = []
        this.selectedRowKeys.forEach(item => {
          arr.push(item)
        })
        deleteCase(arr).then(res => {
            // console.log(res)
            // 刷新表格
            this.$refs.table.refresh()
            this.$message.success('删除成功')
          })
      }
    },
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      this.mdl = { ...record }
      this.visible = true
    },
    handleCheck (record) {
      console.log('record===', record)
      // localStorage.setItem('enterInfo', JSON.stringify({
      //   ...record,
      //   declarationSystemId: record.id,
      //   declarationInfoId: record.declarationInfoId,
      //   userId: record.userId,
      //   socialOrganizationTypeId: record.socialOrganizationId
      // }))
      localStorage.setItem('enterInfo', JSON.stringify({ ...record, declarationInfoId: record.declarationInfoId, status: 2 }))
      this.$router.push('/case/detail')
    },
    handleDelete (record) {
      this.$confirm({
        title: '删除确认',
        content: '确认要删除该数据吗？并且不可恢复！',
        okType: 'danger',
        onOk: () => {
          deleteCase([record.id]).then(res => {
            // 刷新表格
            this.$refs.table.refresh()
            this.$message.success('删除成功')
          })
        },
        onCancel () {
          console.log('Cancel')
        }
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      console.log(form)
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          addCase(values.leader).then(res => {
            // console.log(res)
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.info('新增成功')
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      console.log(this.selectedRowKeys)
    },
    handleReset () {
      this.queryParam = {}
      this.$refs.table.refresh()
    }
  }
}
</script>

<style lang="less" scoped>
</style>
